
import sys
sys.path.append('../')

from flask import (Blueprint, request, session)
from flaskr import Utils
import json

bp = Blueprint('load',__name__, url_prefix='/load')

sheets = None

@bp.route('', methods = ['POST'])
def save():
    global sheets

    sheet_names = request.json.get('sheetNames')


    if('sheets' in session.keys()):
        sheets = session['sheets']
    else:
        session['sheets'] = []
        sheets = []

    if('data' in session.keys()):
        data = session['data']  # 拿到上传表的json

    else:
        return{
            'code': '500',
            'msg': '未上传任何数据源',
        }

    if 'database' in data.keys() and data['database']:
        table_list = list(data['md5s'].keys()) # 上传时的所有的表名
        for name in sheet_names:
            table_list.remove(name)

        for table_name in table_list:
            Utils.removePkl(data['md5s'][table_name])

    json_list = []

    count = 0
    for name in sheet_names:
        obj = {}

        old_name = name

        name = checkName(name)
        md5 = None

        obj['md5'] = None
        obj['md5s'] = None

        if 'md5' in data.keys():
            md5 = data['md5']

        if 'md5s' in data.keys():
            md5 = data['md5s'][name]

        if md5 is not None:
            obj['md5'] = md5

        obj['sheetName'] = old_name
        obj['showName'] = name

        obj['json'] = data['sheetJson'][old_name]
        obj['table'] = data['sheetTable'][old_name]
        sheet_json = data['sheetJson'][old_name]

        df = Utils.jsonToDataFrame(sheet_json)

        obj['columns'] = Utils.getColumns(df)
        obj['types'] = Utils.getTypes(df)

        if 'database' in data.keys() and data['database']:
            obj['database'] = True

        sheets.append(obj)
        session['sheets'] = sheets

        json_list.append(obj)

    return {
        'code' : 200,
        'msg' : '加载成功',
        'data': json_list
    }

        
def checkName(name):
    global sheets

    same_count = 0


    #如果存在这个key 那么重命名
    for sheet in sheets:
        
        if('sheetName' in sheet.keys() and sheet['sheetName'] == name):
            same_count += 1

    if(same_count >= 1):
        return name + "("+ str(same_count+1) + ")"
                
    return name

@bp.route('/getLoad', methods = ['GET'])
def get():
    sheets = None
    if('sheets' in session.keys()):
        sheets = session['sheets']

    if(sheets is None):
        return{
            'code': 200,
            'msg': '没有任何数据加载',
            'data': '[]'
        }

    else:
        return{
            'code': 200,
            'msg': '获取成功',
            'data' : json.dumps(sheets),
        }